﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Account;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using B.S.BasicData.Infrastructure.Utils;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Account
{
    public class UpdateAccountHandler : IRequestHandler<UpdateAccountCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ILogger<UpdateAccountHandler> logger;
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<LogModel> logRepo;

        public UpdateAccountHandler(IMapper mapper,ILogger<UpdateAccountHandler> logger,IBaseRepository<AccountModel> accountRepo,IBaseRepository<LogModel> logRepo)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.accountRepo = accountRepo;
            this.logRepo = logRepo;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(UpdateAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model = mapper.Map<AccountModel>(request);


            var r =  accountRepo.UpdateAsync(model).Result;
            //automapper 
           
            if (r > 0)
            {
                result.Code = ApiEnums.UpdateAccountOk;
                result.Msg = ApiEnums.UpdateAccountOk.Descrption();
                result.Data = r;

                
                //日志
                var logr = logRepo.CreateAsync(new LogModel()
                {
                    Id = YitIdHelper.NextId(),
                    CreateName = model.AccountName,
                    LogContent = result.Msg,
                    CreatTime = DateTime.Now,

                }).Result;

                result.Data = logr;

            }
            else
            {
                result.Code = ApiEnums.Fail;
                result.Msg = ApiEnums.Fail.Descrption();
                result.Data = r;

                //日志
                var logr = logRepo.CreateAsync(new LogModel()
                {
                    Id = YitIdHelper.NextId(),
                    CreateName = model.AccountName,
                    LogContent = result.Msg,
                    CreatTime = DateTime.Now,

                }).Result;

                result.Data = logr;
            }

            return Task.FromResult(result);

        }
    }
}
